module Net
(
 port,
 tcpSocket,
 localhost,
 sendData,
 receiveData,
 getAddr
)where

import qualified Data.ByteString.Lazy as BL

import Network.BSD
import Network.Socket hiding (send, recv)
import Network.Socket.ByteString.Lazy

import Text.Printf
import Data.Word (Word16)

port :: Int
port = 4444

tcpSocket :: IO Socket
tcpSocket = socket AF_INET Stream defaultProtocol

localhost :: HostAddress
localhost = 0x0100007F


getAddr = do
  addr <- inet_addr test_host -- 错误的地址会出异常
  return $ SockAddrInet (fromIntegral test_port) addr
 where
  test_port = 4444
  test_host = "127.0.0.1"

sendData :: Socket -> BL.ByteString -> IO ()
sendData sock msg = do
  sendAll sock msg
  printf $ "Bytes sent "

receiveData :: Socket -> IO ()
receiveData sock = do
  byte <- recv sock $ 20240 * 2
  printf $ "Received " ++ show byte
